<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/3/11/011
 * Time: 8:51
 */

namespace app\project\controller;


use app\common\controller\Common;
use app\index\controller\Base;
use app\project\service\AdvancePlanService;
use app\project\service\PublicService;
use think\Db;
use think\Exception;
use think\Session;
use think\Validate;

/**
 * 项目管理
 * Class Index
 * @package app\project\controller
 */
class Index extends Base
{

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $show = "entry";
        $this->assign("show", $show);
        $library = empty($_GET['library']) ? 0 : $_GET['library'];
        $this->assign("library", $library);
    }

    /**
     * 列表
     */
    public function index()
    {

        if(1==1){
            $library = empty($_GET['library']) ? 0 : $_GET['library'];
            $sessionLibrary =  Session::get("library");
            if (!empty($library) & empty($sessionLibrary)) {
                Session::set("library",$library);
            }
            $where['library'] = ['like', "%{$library}%"];

            $this->assign("library", $library);
            if (!empty($_GET['start']) && $library!=$sessionLibrary) {
                Session::delete("library");
                Session::delete("page");

                Session::delete("duty_unit");
                Session::delete("keyword");
                Session::delete("reply");
                Session::delete("code");
                Session::delete("nature");
                Session::delete("visit_remark");
                Session::delete("project_status");
                Session::delete("warehousing");
                Session::delete("start_status");
                Session::delete("sign");
                Session::delete("duty_person");
                Session::delete("project_type");
                Session::delete("enterprise");
                Session::delete("leader");
                Session::delete("operation");
                Session::delete("condition_val");
                Session::delete("menuTop");
            }
            if (!empty($_GET['visit_remark'])) {
                $visit_remark = $_GET['visit_remark'];
                Session::set("visit_remark",$visit_remark);
                $where['visit_remark'] = ['like', "%{$visit_remark}%"];
            }

            if (!empty($_GET['keyword'])) {
                $keyword = $_GET['keyword'];
                Session::set("keyword",$keyword);
                $where['title'] = ['like', "%{$keyword}%"];
            }
            if (!empty($_GET['code'])) {
                $code = $_GET['code'];
                Session::set("code",$code);
                $where['code'] = ['like', "%{$code}%"];
            }


            if (!empty($_GET['nature'])) {
                $nature = $_GET['nature'];
                Session::set("nature",$nature);
                $where['nature'] = $nature;
            }

            if (!empty($_GET['project_status'])) {
                $project_status = $_GET['project_status'];
                Session::set("project_status",$project_status);
                $where['project_status'] = $project_status - 1;
            }


            if (!empty($_GET['sign'])) {
                $where['sign'] = $_GET['sign'];
                Session::set("sign", $_GET['sign']);
            }
            if (!empty($_GET['start_status'])) {
                $where['start_status'] = $_GET['start_status'];
                Session::set("start_status", $_GET['start_status']);
            }
            if (!empty($_GET['warehousing'])) {
                $where['warehousing'] = $_GET['warehousing'];
                Session::set("warehousing", $_GET['warehousing']);
            }

            if (!empty($_GET['reply'])) {
                $where['reply'] = $_GET['reply'];
                Session::set("reply", $_GET['reply']);
            }


            if (!empty($_GET['duty_unit'])) {
                $duty_unit = $_GET['duty_unit'];
                Session::set("duty_unit", $_GET['duty_unit']);
                $where['duty_unit'] = ['like', "%{$duty_unit}%"];
            }

            if (!empty($_GET['leader'])) {
                $leader = $_GET['leader'];
                Session::set("leader", $_GET['leader']);
                $where['leader'] = ['like', "%{$leader}%"];
            }
            if (!empty($_GET['operation'])) {
                Session::set("operation", $_GET['operation']);
                $where['operation'] = $_GET['operation'];
            }
            if (!empty($_GET['condition_val'])) {
                Session::set("condition_val", $_GET['condition_val']);
                $where['condition_val'] = $_GET['condition_val'];
            }



            if (!empty($_GET['menuTop'])) {
                Session::set("menuTop", $_GET['menuTop']);
                $where['menuTop'] = $_GET['menuTop'];
            }


            if (!empty($_GET['duty_person'])) {
                $duty_person = $_GET['duty_person'];
                Session::set("duty_person", $_GET['duty_person']);
                $where['duty_person'] = ['like', "%{$duty_person}%"];
            }
            if (!empty($_GET['project_type'])) {
                $project_type = $_GET['project_type'];
                Session::set("project_type", $_GET['project_type']);
                $where['project_type'] = ['like',"%".$project_type."%"];
            }
            if (!empty($_GET['enterprise'])) {
                $enterprise = $_GET['enterprise'];
                Session::set("enterprise", $_GET['enterprise']);
                $where['enterprise'] = $enterprise;
            }

            if (!empty($_GET['pro_group'])) {
                $pro_group = $_GET['pro_group'];
                $where['pro_group'] = $pro_group;
            }

            if (!empty($_GET['plan_category'])) {
                $plan_category = $_GET['plan_category'];
                $where['plan_category'] = $plan_category;
            }


            $this->setSession("duty_unit");
            $this->setSession("keyword");
            $this->setSession("reply");
            $this->setSession("code");
            $this->setSession("nature");
            $this->setSession("visit_remark");
            $this->setSession("project_status");
            $this->setSession("warehousing");
            $this->setSession("start_status");
            $this->setSession("sign");
            $this->setSession("duty_person");
            $this->setSession("project_type");
            $this->setSession("enterprise");
            $this->setSession("leader");
            $this->setSession("operation");
            $this->setSession("condition_val");
            $this->setSession("menuTop");

//        $duty_unit = Session::get("duty_unit");
//        $this->assign("duty_unit",$duty_unit);
//        $reply = Session::get("reply");
//        $this->assign("reply",$reply);
//        $keyword = Session::get("keyword");
//        $this->assign("keyword",$keyword);
//        $code = Session::get("code");
//        $this->assign("code",$code);
//        $nature = Session::get("nature");
//        $this->assign("nature",$nature);
//        $visit_remark = Session::get("visit_remark");
//        $this->assign("visit_remark",$visit_remark);
//        $project_status = Session::get("project_status");
//        $this->assign("project_status",$project_status);
//        $warehousing = Session::get("warehousing");
//        $this->assign("warehousing",$warehousing);
//        $start_status = Session::get("start_status");
//        $this->assign("start_status",$start_status);
//        $sign = Session::get("sign");
//        $this->assign("sign",$sign);
//        $duty_person = Session::get("duty_person");
//        $this->assign("duty_person",$duty_person);
//        $project_type = Session::get("project_type");
//        $this->assign("project_type",$project_type);
//        $enterprise = Session::get("enterprise");
//        $this->assign("enterprise",$enterprise);
//        $leader = Session::get("leader");
//        $this->assign("leader",$leader);
//        $operation = Session::get("operation");
//        $this->assign("operation",$operation);
//        $condition_val = Session::get("condition_val");
//        $this->assign("condition_val",$condition_val);
//        $menuTop = Session::get("menuTop");
//        $this->assign("menuTop",$menuTop);

            $common = new Common();
            $page = empty($_GET['page']) ? 1 : $_GET['page'];

            $showPage = Session::get("page");
            $showPage = empty($showPage) ? 1 : $showPage;
            $this->assign("showPage", $showPage);
            Session::set("page", $page);

            //查询责任单位
            $project_dictionaries = $common->public_select("project_dictionaries", ['status' => 1], "id,name")->select();
            $this->assign("project_dictionaries", $project_dictionaries);

            $plan_category = \think\Config::get("plan_category");
            $this->assign("plan_category", $plan_category);

            //项目类别
            $type = $common->public_select("project_type", ['status' => 1,'type'=>1], 'id,name')->select();
            $this->assign("type", $type);

            //项目类别
            $enterprise = $common->public_select("project_type", ['status' => 1,'type'=>3], 'id,name')->select();
            $this->assign("enterprise", $enterprise);

            //责任人
            $account = $common->public_select("project_account", ['status' => 1], 'id,name')->select();
            $this->assign("account", $account);


            $pro_group = \think\Config::get("pro_group");
            $this->assign("pro_group", $pro_group);
        }

        //查询下级项目
        $parent_id = empty($_GET['parent_id'])?0:$_GET['parent_id'];
        $this->assign("parent_id", $parent_id);
        if(!empty($parent_id)){
            $where['parent_id'] = $parent_id;
        }
        //查询下级项目end


//        $sign = [1=>"未签约",2=>"已签约",3=>"已逾期",4=>"无法签约"];

        if (!empty($_GET['type'])) {
            try {
                $limit = empty($_GET['limit']) ? 10 : $_GET['limit'];
                $start = ($page - 1) * $limit;
                $thisWechat = Session::get("thisWechat");
                $where['uniacid'] = $thisWechat['id'];
//                $limit = 800;

                $beginTime=mktime(0,0,0,date("m"),01,date("Y"));
                $endTime=mktime(23,59,59,date("m"),date("t"),date("Y"));
          

                if($library==6){
                    $order = "visit_time desc,sort desc,id desc";
                }else{
                    $order = "sort desc,parent_id desc,id desc";
                }

                if(!empty($_GET['reorder'])){
                    $reorder = $_GET['reorder'];
                    if(!empty($reorder['type']) & !empty($reorder['field'])){
                        $order = $reorder['field']." ".$reorder['type'];
                    }
                }

                $warehousing = [1=>"待入库",2=>"已入库"];
                if (!empty($_GET['typeId'])) {
                    $typeId = $_GET['typeId'];
                    //获取责任单位
                    $dictionarie = PublicService::ListService("project_dictionaries",['typeId'=>$typeId],"name");
           
                    
                    if(empty($dictionarie)){
                        $whereOr['duty_unit'] = "-1";
                    }else{
                        if(count($dictionarie)>1){
                            foreach ($dictionarie as $itme){
                                $whereOr['duty_unit'][] = ['like', "%{$itme['name']}%"];
                            }
                        }else{
                            foreach ($dictionarie as $itme){
                                $whereOr['duty_unit'] = ['like', "%{$itme['name']}%"];
                            }
                        }
                    }
                }
                if(!empty($whereOr)){
                    $list = Db::name("project_pro")->where(function($query) use ($whereOr) {
                        $query->whereor($whereOr);
                    })->where($where)->limit($start, $limit)->order($order)->group("title")->select();
                    $count = Db::name("project_pro")->where(function($query) use ($whereOr) {
                        $query->whereor($whereOr);
                    })->where($where)->group("title")->count();
                }else{
                    $list = $common->public_select("project_pro", $where, null)
                        ->limit($start, $limit)->order($order)->group("title")->select();

                    $count = $common->public_select("project_pro", $where)->group("title")->count();
                }


                $parentIds = [];
                foreach ($list as $v) {
                    if ($v['parent_id'] > 0) {
                        $parentIds[] = $v['parent_id'];
                    }
                }

//                $parentNames = [];
//                if (count($parentIds) > 0) {
//                    $whereParent['id'] = ['in', $parentIds];
//                    $parentNames = $common->public_select("project_pro", $whereParent, 'id,title')->select();
//                }
//
//                $temp = [];
//                foreach ($parentNames as $v) {
//                    $temp[$v['id']] = $v['title'];
//                }
//                $parentNames = $temp;
//                unset($temp);

                foreach ($list as $k => $v) {
//                    $list[$k]['parent_name'] = isset($parentNames[$v['parent_id']]) ? $parentNames[$v['parent_id']] : '--';

                    //获取下级项目数
                    unset($where);
                    $where['parent_id'] = $v['id'];
                    $list[$k]['parentCount'] = Db::name("project_pro")->where($where)->count("*");



                    $list[$k]['addtime'] = empty($v['updatetime'])?$v['addtime']:$v['updatetime'];

                    $list[$k]['warehousing'] = empty($warehousing[$v['warehousing']])?"":$warehousing[$v['warehousing']];

                    $figureWhere = [];
                    //查询本月是否有走访记录
                    $figureWhere['pro_id'] = $v['id'];
                    $figureWhere['show_time'] = ['like',"%".date("Y-m")."%"];
                    $figureCount = $common->public_select("project_pro_figure",$figureWhere)->count('*');
                    $list[$k]['figureCount'] = $figureCount;
                    $list[$k]['isUpdate'] = empty($figureCount)?"否":"是";

//                    $list[$k]['project_status'] = empty($v['project_status']) ? "正常" : "逾期";
                    $list[$k]['page'] = intval($page);
                    $planWhere = [];
                    $declare = '';
                    //查询上个月是否申报
                    $lastMonth = date('m', strtotime('-1 month'));  //上月
//                    $currentMonth = date('m');  //本月
                    $planWhere['year'] = date("Y");
                    $planWhere['pro_id'] = $v['id'];
                    $plandetail = $common->public_select("project_pro_plandetail", $planWhere)->find();
                    if (!empty($plandetail)) {
                        $planWhere['month'] = intval($lastMonth);
                        $declare = $common->public_select("project_pro_plandetail", $planWhere)->value("declare");
//                        $list[$k]['project_status'] = empty($declare) ? "逾期" : "正常";
                    }


                    //计划签约时间
                    $signDays = 0;
                    if(!empty($v['signTime'])){
                        $startdate = strtotime(date("Y-m-d"));
                        $enddate = strtotime($v['signTime']);
                        $signDays=round(($enddate-$startdate)/3600/24) ;
                    }
                    $list[$k]['signDays'] = $signDays;

                    //计划开工时间
                    $onstreamTimeDays = 0;
                    if(!empty($v['plan_onstream_time'])){
                        $startdate = strtotime(date("Y-m-d"));
                        $enddate = strtotime($v['plan_onstream_time']);
                        $onstreamTimeDays=round(($enddate-$startdate)/3600/24) ;
                    }
                    $list[$k]['onstreamTimeDays'] = $onstreamTimeDays;

                    //计划开工时间
                    $completeTimeDays = 0;
                    if(!empty($v['plan_complete_time'])){
                        $startdate = strtotime(date("Y-m-d"));
                        $enddate = strtotime($v['plan_complete_time']);
                        $completeTimeDays=round(($enddate-$startdate)/3600/24) ;
                    }
                    $list[$k]['completeTimeDays'] = $completeTimeDays;

//                    $list[$k]['sign'] = $sign[$v['sign']];

//                    $pro_type = config("pro_type");
//                    $list[$k]['menuTop'] = empty($pro_type[$v['menuTop']])?"":$pro_type[$v['menuTop']];
//                    $typeWhere = [];
//                    $typeWhere['id'] = $v['enterprise'];
//                    $list[$k]['enterprise'] = Db::name("project_type")->where($typeWhere)->value("name");
//
//                    if($v['menuTop']==1){
//                        $cultivation = [1=>"计划年度进规企业",2=>"计划月度进规企业"];
//                        $list[$k]['cultivation'] = empty($cultivation[$v['cultivation']])?"":$cultivation[$v['cultivation']];
//                    }else{
//                        $cultivation = [1=>"运行正常企业",2=>"一般困难企业",3=>"特别困难企业",4=>"停产企业"];
//                        $list[$k]['cultivation'] = empty($cultivation[$v['condition_val']])?"":$cultivation[$v['condition_val']];
//                    }

                    //查询是否存在领导点评且未得到回复的信息
                    $commentWhere['pro_id'] = $v['id'];
                    $commentWhere['type'] = 0;
                    $commentWhere['reply'] = 0;
                    $commentWhere['pid'] = 0;
                    //更新脚本
                    /*$commentList = $common->public_select("project_pro_comment", $commentWhere)->select();
                    if(count($commentList)>0){
                        foreach ($commentList as $k=>$v){
                            $newCount = 0;
                            $newCount = $common->public_select("project_pro_comment", ['pid'=>$v['id']])->count("*");
                            if($newCount>0){
                                $common->public_select("project_pro_comment", ['id'=>$v['id']])->update(['reply'=>1]);
                            }
                        }
                    }*/

                    $commentCount = 0;
                    $commentCount = $common->public_select("project_pro_comment", $commentWhere)->count("*");
                    $list[$k]['commentCount'] = $commentCount;

                    //推进计划未审核
                    $advanceCount = 0;
                    $advanceWhere['pro_id'] = empty($v['pid'])?$v['id']:$v['pid'];
                    $advanceWhere['content'] = ['neq',''];
                    $advanceWhere['status'] = 0;
                    $advanceCount = $common->public_select("project_pro_advance_plan", $advanceWhere)->count("*");
                    $list[$k]['advanceCount'] = $advanceCount;

                    //进展情况
                    $progressCount = 0;
                    $progressWhere['pid'] = empty($v['pid'])?$v['id']:$v['pid'];
                    $progressWhere['addtime'][] = ['gt',$beginTime];
                    $progressWhere['addtime'][] = ['elt',$endTime];
                    $progressCount = $common->public_select("project_progress", $progressWhere)->count("*");
                    $list[$k]['progressCount'] = $progressCount;

                }

                $black['code'] = 0;
                $black['data'] = $list;
                $black['count'] = $count;
                $black['page'] = $showPage;

            } catch (Exception $e) {
                $black['code'] = 202;
                $black['line'] = $e->getLine();
                $black['msg'] = $e->getMessage();
            }
            return $black;
        }else{
            $Communal = new Communal();
            //获取产业链数据
            $IndustrialChain = $Communal->dictionary("project_type",2);
            $this->assign('IndustrialChain',$IndustrialChain);
        }
        return $this->fetch("index");
    }

    public function setSession($key){
        $value = Session::get($key);
        $this->assign($key,$value);
    }

    /**
     * 详情
     */
    public function detail()
    {
        $common = new Common();
        $thisWechat = Session::get("thisWechat");
        //责任单位
        $Communal = new Communal();
        $duty_unit = $Communal->dictionary("project_dictionaries");
        $this->assign("duty_unit", json_encode($duty_unit));

        //责任人
        $accountWhere['uniacid'] = $thisWechat['id'];
        $account = $common->public_select("project_account", $accountWhere, "id value,name title")->select();
        $this->assign("account", json_encode($account));

        //项目类别
        $pro_type = $Communal->dictionary("project_type",1);
        $library = empty($_GET['library']) ? 0 : $_GET['library'];
        if (!empty($_GET['id'])) {
            $where['id'] = $_GET['id'];
            $where['uniacid'] = $thisWechat['id'];
            $detail = $common->public_select("project_pro", $where)->find();
            $detail['project_type'] = explode(",",$detail['project_type']);

            $duty_unit_v = explode(";", trim($detail['duty_unit'], ";"));
            $duty_unit_k = $this->takekey($duty_unit, $duty_unit_v);

            $duty_person_v = explode(";", trim($detail['duty_person'], ";"));
            $duty_person_k = $this->takekey($account, $duty_person_v);

            $leader_v = explode(";", trim($detail['leader'], ";"));
            $leader_k = $this->takekey($account, $leader_v);

            $assign['duty_unit_k'] = json_encode($duty_unit_k);
            $assign['duty_person_k'] = json_encode($duty_person_k);
            $assign['leader_k'] = json_encode($leader_k);
            $this->assign($assign);
            $parentId = $detail['parent_id'];
        }else{
            $queryTable = Db::query("show columns from us_project_pro"); //获取表结构
            foreach ($queryTable as $item) {
                $detail[$item['Field']] = "";
            };
            $detail['project_type'] = [];
            $assign['duty_unit_k'] = "{}";
            $assign['duty_person_k'] = "{}";
            $assign['leader_k'] = "{}";
            $this->assign($assign);
            $detail['library'] = $library;
            $parentId = isset($_GET['parent_id']) ? $_GET['parent_id'] : 0;
        }

        if(empty($detail['lng'])){
//            $detail['lng'] = "111.788328";
//            $detail['lat'] = "30.820948";
            $detail['lng'] = "";
            $detail['lat'] = "";
        }

        
        $this->assign("detail", $detail);
        $this->assign("library", $library);
        $this->assign("parentId", $parentId);
        switch ($library){
            case 1:
                //所属产业链
                $IndustrialChain = $Communal->dictionary("project_type",2);
                $this->assign("IndustrialChain", $IndustrialChain);
                $template = "saveView1";
                break;
            case 2:
                //一级分类
                $typeWhere['pid'] = 0;
                $typeWhere['status'] = 1;
                $typeWhere['type'] = 4;
                $parent = $common->public_select("project_type",$typeWhere)->select();
                $this->assign("parent", $parent);


//                if (!empty($_GET['id'])) {
//                    $pro_type = Db::name("project_type")->where(['pid'=>$detail['menuTop']])->field("id as value,name as title")->select();
//                }

                $template = "saveView2";
                break;
            case 3:
                //一级分类
                $typeWhere['pid'] = 0;
                $typeWhere['status'] = 1;
                $typeWhere['type'] = 4;
                $parent = $common->public_select("project_type",$typeWhere)->select();
                $this->assign("parent", $parent);

//                if (!empty($_GET['id'])) {
//                    $pro_type = Db::name("project_type")->where(['pid'=>$detail['menuTop']])->field("id as value,name as title")->select();
//                }

                $template = "saveView3";
                break;
            case 4:
//                $template = empty($_GET['id']) ? "addView" : "saveView";
                $template = "saveView";
                break;
            case 5:
                $template = "saveView5";
                break;
            case 6:
                //企业一级分类
                $pro_type = config("pro_type");
                $this->assign('pro_type',$pro_type);
                if (!empty($_GET['id'])) {
                    //企业类型
                    if(!empty($detail['menuTop'])){
                        $typeWhere['menuTop'] = $detail['menuTop'];
                        $typeWhere['status'] = 1;
                        $enterprise = Db::name("project_type")->where($typeWhere)->field("id as value,name as title")->select();
                    }else{
                        $enterprise = [];
                    }

                }else{
                    //企业类型
                    $enterprise = [];
                }

                //进规类型
                $cultivation = \think\Config::get("cultivation");
                $this->assign("cultivation", $cultivation);

                $this->assign("enterprise", $enterprise);
                $template = "saveView6";
                break;
        }

        $this->assign("pro_type", $pro_type);
        return $this->fetch($template);
    }

    /**
     * 添加操作
     */
    public function add()
    {
        $data = $this->request->post();
        $common = new Common();
        try {
            $id = $this->operation($common, $data);
            $log['remark'] = "【工程管理】用户【" . Session::get("user_name") . "】添加项目,项目id【" . $id . "】";
            $common->addLog($log);
            $black['code'] = 0;
            $black['msg'] = "添加成功";
        } catch (Exception $e) {
            Db::rollback();
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    /**
     * 修改操作
     */
    public function save()
    {
        $data = $this->request->post();
        $common = new Common();
        try {
            $id = $this->operation($common, $data);
            $log['remark'] = "【工程管理】用户【" . Session::get("user_name") . "】修改项目,项目id【" . $id . "】";
            $common->addLog($log);
            $black['code'] = 0;
            $black['msg'] = "添加成功";
        } catch (Exception $e) {
            Db::rollback();
            $black['code'] = 202;
            $black['line'] = $e->getLine();
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    //数据操作
    public function operation($common, $data)
    {
        // 提取公共处理 library 的方法
        $handleLibrary = function ($data, $flagValue, $removeValue) {
            $library = explode(",", (string)$data['library']);
            foreach ($library as $k => $v) {
                if ($v == $removeValue) {
                    unset($library[$k]);
                }
            }
            if (!in_array((string)$flagValue, $library)) {
                $library[] = (string)$flagValue;
            }
            return implode(",", array_filter($library));
        };

        // sign 处理
        if (!empty($data['sign'])) {
            switch ($data['sign']) {
                case 1:
                    $data['library'] = $handleLibrary($data, 2, 2);
                    break;
                case 2:
                    $data['library'] = $handleLibrary($data, 2, 2);
                    break;
            }
        }

        // start_status 处理
        if (!empty($data['start_status'])) {
            switch ($data['start_status']) {
                case 1:
                    $data['library'] = $handleLibrary($data, 3, 3);
                    break;
                case 2:
                    $data['library'] = $handleLibrary($data, 3, 3);
                    break;
            }
        }

        // warehousing 处理
        if (!empty($data['warehousing'])) {
            switch ($data['warehousing']) {
                case 1:
                    $data['library'] = $handleLibrary($data, 5, 5);
                    break;
                case 2:
                    $data['library'] = $handleLibrary($data, 5, 5);
                    break;
            }
        }

        $thisWechat = Session::get("thisWechat");
        $this->condition($data);

        $data['duty_unit'] = rtrim(ltrim($data['duty_unit'], ";"), ";");

        if (!empty($data['duty_person'])) {
            $data['duty_person'] = rtrim(ltrim($data['duty_person'], ";"), ";");
        }
        if (!empty($data['leader'])) {
            $data['leader'] = rtrim(ltrim($data['leader'], ";"), ";");
        }

        if (empty($data['id'])) {
            $data['uniacid'] = $thisWechat['id'];
            $data['addtime'] = date("Y-m-d H:i:s");
            $data['add_id'] = Session::get("id");
        } else {
            $codeWhere['id'] = ['neq', $data['id']];
            $data['updatetime'] = date("Y-m-d H:i:s");
            $data['update_id'] = Session::get("id");
        }

        /*if (!empty($data['code'])) {
            $codeWhere['code'] = $data['code'];
            $codeblack = $common->public_select("project_pro", $codeWhere)->find();
            if (!empty($codeblack)) {
                throw new Exception("项目代码重复");
            }
        }*/

        if (!empty($data['project_type'])) {
            $data['project_type'] = implode(",", $data['project_type']);
        } else {
            $data['project_type'] = "";
        }

        // 同步更新数据
        $projectDb = Db::name("project_pro"); // 缓存数据库对象

        if (!empty($data['id'])) {
            $synchroData = $data;
            unset($synchroData['id']);
            unset($synchroData['library']);
            $synchroWhere['pid'] = $data['id'];
            $projectDb->where($synchroWhere)->update($synchroData);

            // 查询是否是拷贝项目
            $copyWhere['id'] = $data['id'];
            $pid = $projectDb->where($copyWhere)->value("pid");
            if (!empty($pid)) {
                unset($synchroWhere);
                $synchroWhere['id'] = $pid;
                $projectDb->where($synchroWhere)->update($synchroData);
            }
        } else {
            $data['cause'] = '';
        }

        if (!empty($data['lin'])) {
            if ($data['lng'] == "111.788328") {
                $data['lng'] = "";
                $data['lat'] = "";
            }
        }

        $id = $common->handle("project_pro", $data, 1);

        /*if (!empty($data['actualsignTime']) && in_array($data['library'], [2,3,4])) {
            $detail = $projectDb->where(['id'=>$id])->field("id,pid,plan_category")->find();
            if ($detail['plan_category'] == 2) {
                $actualsignTime = $data['actualsignTime'];
                $array = [343,344,350];
                $plantime[0] = date("Y-m-d", strtotime("+3 Month", strtotime($actualsignTime)));
                $plantime[1] = date("Y-m-d", strtotime("+7 Month", strtotime($actualsignTime)));
                $plantime[2] = date("Y-m-d", strtotime("+31 Month", strtotime($actualsignTime)));
                //推进计划更新
                foreach ($array as $k=>$v){
                    unset($advdata);
                    $advdata['pro_id'] = empty($detail['pid'])?$detail['id']:$detail['pid'];
                    $advdata['type_id'] = $v;
                    $advDetail = AdvancePlanService::detailService($advdata);
                    $advdata['id'] = empty($advDetail)?0:$advDetail['id'];
                    $advdata['time'] = $plantime[$k];
                    $advdata['color'] = 0;
                    AdvancePlanService::saveService($advdata);
                }
            }
        }*/

        return $id;
    }


    /**
     * 删除操作
     */
    public function del()
    {
        try {
            $common = new Common();
            $id = $_POST['id'];

            $list = $common->public_select("project_pro", ['id' => ['in', $id]], "id,title,library")->select();
            $res = $common->public_select("project_pro", ['id' => ['in', $id]])->delete();
            $common->public_select("project_pro_figure", ['pro_id' => ['in', $id]])->delete();
            $common->public_select("project_pro_plan", ['pro_id' => ['in', $id]])->delete();
            $common->public_select("project_pro_comment", ['pro_id' => ['in', $id]])->delete();
            if (empty($res)) {
                throw new Exception("删除失败");
            }
            foreach ($list as $k => $v) {
                $log['remark'] = "【工程管理】,账号【" . Session::get("user_name") . "】删除项目【" . $v['title'] . "】,关联id【" . $v['id'] . "】";
                $common->addLog($log);
            }
            $black['code'] = 0;
            $black['msg'] = "删除成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    public function takekey($data, $value)
    {
        $black = [];
        foreach ($data as $k => $v) {
            if (in_array($v['title'], $value)) {
                $black[] = $v['value'];
            }
        }
        return $black;
    }


    public function condition($data)
    {
        
     
        if($data['library']==6){
             $rule = [
                ["title", "require", "企业名称不能为空"],
                ["content", "require", "走访情况不能为空"],
//                ["remark", "require", "备注不能为空"],
            ];
        }else{
             $rule = [
                ["title", "require", "项目名称不能为空"],
                ["content", "require", "主要建设内容及规模不能为空"],
//                ["remark", "require", "备注不能为空"],
            ];
            
        }
       
        $validate = new Validate($rule);
        if (!$validate->check($data)) {
            throw new Exception($validate->getError());
        }
        
        if(!empty($data['thumb'])){
            if (!filter_var($data['thumb'], FILTER_VALIDATE_URL)) {
                throw new Exception("缩略图格式有误");
            }
        }
        
         if(!empty($data['planned_production_time'])){
            if (!$this->checkDateFormat($data['planned_production_time'])) {
                throw new Exception("拟投产时间格式有误");
            }
        }
        
        if(!empty($data['signTime'])){
            if (!$this->checkDateFormat($data['signTime'])) {
                throw new Exception("计划签约时间格式有误");
            }
        }
        
        if(!empty($data['cardMeeting'])){
            if (!$this->checkDateFormat($data['cardMeeting'])) {
                throw new Exception("通过论证会时间格式有误");
            }
        }
       if(!empty($data['plan_onstream_time'])){
            if (!$this->checkDateFormat($data['plan_onstream_time'])) {
                throw new Exception("拟开工时间格式有误");
            }
        }
        
        if(!empty($data['onstream_time'])){
            if (!$this->checkDateFormat($data['onstream_time'])) {
                throw new Exception("实际开工时间格式有误");
            }
        }
        if(!empty($data['arrange_onstream_time'])){
            if (!$this->checkDateFormat($data['arrange_onstream_time'])) {
                throw new Exception("合作协议约定开工时间格式有误");
            }
        }
        
        if(!empty($data['actualsignTime'])){
            if (!$this->checkDateFormat($data['actualsignTime'])) {
                throw new Exception("实际签约时间格式有误");
            }
        }
        
        if(!empty($data['arrange_complete_time'])){
            if (!$this->checkDateFormat($data['actualsignTime'])) {
                throw new Exception("合作协议约定竣工时间格式有误");
            }
        }
        
        if(!empty($data['plan_complete_time'])){
            if (!$this->checkDateFormat($data['actualsignTime'])) {
                throw new Exception("拟竣工时间格式有误");
            }
        }

        if(!empty($data['visit_time'])){
            if (!$this->checkDateFormat($data['visit_time'])) {
                throw new Exception("走访时间格式有误");
            }
        }

        if(!empty($data['gauge'])){
            if (!$this->checkDateFormat($data['gauge'])) {
                throw new Exception("拟进规时间格式有误");
            }
        }


    }

    public function checkDateFormat1($date)
    {
        $dateFormat = 'Y-m-d H:i:s';
        $dateObj = \DateTime::createFromFormat($dateFormat, $date);
        return $dateObj && $dateObj->format($dateFormat) === $date;
    }
    
     public function checkDateFormat($date)
    {
        $dateFormat = 'Y-m-d';
        $dateObj = \DateTime::createFromFormat($dateFormat, $date);
        return $dateObj && $dateObj->format($dateFormat) === $date;
    }

}